<?php

namespace App\Api\Controllers;

use App\Jobs\Elesticsearch;
use App\Jobs\PushQueue;
use App\Models\FriendModel;
use App\Models\FriendUser;
use App\Models\JpushMobile;
use App\Models\MediaLike;
use App\Models\MemberShip;
use App\Models\Shareholder;
use App\Models\UserReport;
use App\Models\UserTicket;
use App\Services\Log;
use App\Services\MediaService;
use App\Services\Pusher;
use App\Services\SnsService;
use App\Services\Sts;
use App\Services\UserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use Carbon\Carbon;
use App\Models\User;
use App\Models\Friend;
use App\Exceptions\ApiException;
use App\Api\Controllers\WalletController;
use App\Models\Logic\Wallet;
use App\Models\OrderLog;
use Illuminate\Support\Facades\Redis;
use App\Models\MessagesSentSucceed;
use App\Models\MessagesSentFailure;
use App\Models\ActivityConfig;
use App\Enum\ActivityEnum;
use App\Services\VideoChatService;
use App\Models\UserInvitationCode;

/**
 * 用户中心
 * Class UserController
 * @package App\Api\Controllers
 */
class UserController extends CommonController
{
    public function __construct()
    {
        parent::__construct();
        // 获取用户基本信息
        $this->getUserInfo();
    }

    /**
     * 我的首页
     * @return array
     */
    public function index()
    {
        // 获取用户基本信息
        $return = $this->user_info;
        $return->avatar = getSignUrl($return->avatar);
        return json_success('ok', $return, 10000);
    }

    /**
     * 用户基本信息
     * @return array
     */
    public function baseInfo()
    {
        // 获取用户基本信息
        $return = $this->user_info;
        $return->avatar = getSignUrl($return->avatar);
        return json_success('ok', $return, 10000);
    }

    /**
     * 我的上传列表
     * @return array
     */
    public function uploadList()
    {
        // 分页
        $page = IT('page') ? IT('page') : 1;
        $rows = IT('rows') ? IT('rows') : 10;
        $page = ($page-1)*$rows;

        // 获取用户ID
        $uid = $this->uid;
        // 获取条件
        $select = array(
            'id','title','media','comments','star'
        );
        $where = array(
            ['uid','=',$uid],
            ['status','=',1],
            ['is_delete','=',0]
        );
        $order = 'sorts desc,id desc';
        $data = D('media')
            ->select($select)
            ->where($where)
            ->orderByRaw($order)
            ->offset($page)
            ->limit($rows)
            ->get();
        foreach ($data as $k => $v) {
            $data[$k]->name = $this->user_info->name;
            $data[$k]->images = [];
            $data[$k]->video = '';
//            if ($v->type == 1) {// 视频
//                $data[$k]->vidoe = json_decode($v->media,true)[0];
//            } else if ($v->type == 2) {// 图片
//                $data[$k]->images = json_decode($v->media,true);
//            } else {
//                //
//            }
            unset($data[$k]->media);
        }

        // 评论总数
        $comment_sum = D('media_comment')
            ->where([['uid','=',$uid],['status','=',1],['is_delete','=',0]])
            ->count();
        $return = array(
            'comment_sum' => $comment_sum,
            'media_data'  => $data
        );
        return json_success('ok', $return, 10000);
    }

    /**
     * 我的参与
     * @return array
     */
    public function partakeList()
    {
        // 分页
        $page = IT('page') ? IT('page') : 1;
        $rows = IT('rows') ? IT('rows') : 10;
        $page = ($page-1)*$rows;

        // 获取用户ID
        $uid = $this->uid;
        // 获取条件
        $select = array(
            'id','media_id','content','parent_id'
        );
        $where = array(
            ['uid','=',$uid],
            ['status','=',1],
            ['is_delete','=',0]
        );
        $order = 'sorts desc,id desc';
        $data = D('media_comment')
            ->select($select)
            ->where($where)
            ->orderByRaw($order)
            ->offset($page)
            ->limit($rows)
            ->get();
        foreach ($data as $k => $v) {
            // 一、二级回复
            if ($v->parent_id != 0) {
                $reply = D('media_comment')
                    ->select('uid','content','is_delete')
                    ->where([['id','=',$v->parent_id],['status','=',1]])
                    ->first();
                $data[$k]->reply_uid = $reply->uid;
                $data[$k]->reply_name = D('users')->where([['id','=',$reply->uid]])->value('name');
                if (empty($reply->is_delete)) {
                    $data[$k]->reply_content = $reply->content;
                } else {
                    $data[$k]->reply_content = '该评论已被删除';
                }
            } else {
                $data[$k]->reply_uid = 0;
                $data[$k]->reply_name = '';
                $data[$k]->reply_content = '';
            }
            // 用户的基本信息
            $data[$k]->user_info['uid'] = $this->uid;
            $data[$k]->user_info['name'] = $this->user_info->name;
            $data[$k]->user_info['avatar'] = $this->user_info->avatar;
            // 参与的文章详情
            $media = D('media')
                ->select('id','media','title','type')
                ->where([['id','=',$v->media_id]])
                ->first();
            $media->images = [];
            $media->video = '';
            if ($media->type == 1) {// 视频
                $media->vidoe = json_decode($media->media,true)[0];
            } else if ($media->type == 2) {// 图片
                $media->images = json_decode($media->media,true);
            } else {
                //
            }
            $data[$k]->media = $media;
            unset($media->media);
            unset($data[$k]->parent_id);
            unset($data[$k]->media_id);
        }

        // 我的参与总数
        $comment_sum = D('media_comment')
            ->where([['uid','=',$uid],['status','=',1],['is_delete','=',0]])
            ->count();
        $return = array(
            'comment_sum'  => $comment_sum,
            'comment_data' => $data
        );
        return json_success('ok',$return,10000);
    }

    /**
     * 关注视频列表注列表
     * @return array
     */
    public function collectMediaList()
    {
        // 分页
        $page = IT('page') ? IT('page') : 1;
        $rows = IT('rows') ? IT('rows') : 10;
        $ticket = IT('ticket');
        $ClientSource = IT('ClientSource');
        $page = ($page-1)*$rows;
        // 获取用户id
        $uid = $this->uid;

        $view_user_ticket = UserTicket::where([['ticket',$ticket],['client_source',$ClientSource], ['status',1]])->first();
        $user = $view_user_ticket->_user()->first();

        $data = MediaService::mediaList($uid,$page,$rows);

        foreach ($data as &$media) {
            $media->protected_avatar = !empty($media->avatar) ? $media->avatar : '';
            $media->protected_media = !empty($media->media) ? $media->media : '';
            $media->is_star = ($user && $user->_mediaStars()->where('media_id',$media->id)->first()) ? 1 : 0;
            $media->media = getSignUrl($media->media);
            $media->cover = getSignUrl($media->cover);
            $media->avatar = getSignUrl($media->avatar);
            $media->username = $media->name;
            $media_like = MediaLike::where([['media_id', $media->id], ['uid', $uid]])->first();
            $media->is_like = $media->is_like ? 1 : 0;

            $media->is_friend = 0;
            $media->is_attention = 0;
            // 登录状态，非自己
            if(!empty($view_user_ticket) && $view_user_ticket->uid != $media->uid){
                // 亲友
                $friend_rows_id = FriendModel::getRowsObj([['uid', '=', $view_user_ticket->uid],['friend_uid', '=', $media->uid], ['status', '=', '1']], 'id');
                // 关注好友状态
                $friend_user_rows_id = FriendUser::getRowsObj([['uid', '=', $view_user_ticket->uid],['friend_id', '=', $media->uid], ['status', '=', '1'], ['type','=', 3]], 'id');
                if(!empty($friend_rows_id))
                    $media->is_friend = 1;
                if(!empty($friend_user_rows_id))
                    $media->is_attention = 1;
            }

            unset($media->name);
        }
        unset($media);
        return json_success('ok', $data, 10000);
    }


    /**
     * 观看记录列表
     * @return array
     */
    public function historyList()
    {
        // 分页
        $page = IT('page') ? IT('page') : 1;
        $rows = IT('rows') ? IT('rows') : 10;
        $page = ($page-1)*$rows;

        // 获取用户id
        $uid = $this->uid;
        // 获取条件
        $select = array(
            'media_history.id','media.title','media.comments','media.star','media.media',
            'media.type','users.name'
        );
        $where = array(
            ['media_history.uid','=',$uid],
            ['media_history.status','=',1],
            ['media.status','=',1],
            ['media.is_delete','=',0]
        );
        $order = 'media_history.sorts desc,media_history.id desc,media.sorts desc,media.id desc';
        $data = D('media_history')
            ->select($select)
            ->leftJoin('media','media_history.media_id','=','media.id')
            ->leftJoin('users','media.uid','=','users.id')
            ->where($where)
            ->orderByRaw($order)
            ->offset($page)
            ->limit($rows)
            ->get();
        // 三种类型，视频、图片、纯文章
        foreach ($data as $k => $v) {
            if(empty($data[$k]->media)){
                $data[$k]->media = [];
            }
        }
        return json_success('ok', $data, 10000);
    }

    public function delHistory()
    {
        // 获取数据
        $history_id = IT('history_id',true);
        $uid = $this->uid;

        // 防止用户频繁操作删除观看记录
        if (cache('history_del_history' . $uid)) {
            EE('请勿频繁操作', 0, 10113);
        }
        cache(['history_del_history' . $uid => $uid], Carbon::now()->addSecond(1));
        DB::beginTransaction();
        $history = D('media_history')
            ->where(['id' => $history_id, 'uid' => $uid])
            ->first();
        if(empty($history)){
            EE("该观看记录不存在!", 0, 10114);
        }
        // 删除文章
        $res = D('media_history')
            ->where(['id' => $history_id, 'uid' => $uid,'status' =>1])
            ->delete();
        if (empty($res)) {
            DB::rollBack();
            return json_error('操作失败',[], 10001);
        }
        DB::commit();
        return json_success('成功删除', [], 10115);
    }

    /**
     * 编辑昵称首页
     * @return array
     */
    public function editNickname()
    {
        // 获取昵称
        $user_info = $this->user_info;
        $return = array(
            'nick_name' => $user_info->name
        );
        return json_success('ok', $return, 10000);
    }

    /**
     * 确认编辑昵称
     * @return array
     */
    public function editNicknameSubmit()
    {
        // 输入昵称
        $nick_name = IT('nick_name',true,'请输入昵称', 10116);

        // 判断昵称规范
        if (mb_strlen($nick_name) > 12 && strlen($nick_name) > 16) {
            EE('昵称过长请重试',0, 10117);
        }
        // 更新条件及更新信息
        $user_info = $this->user_info;

        $where = array(
            ['id','=',$user_info->id]
        );
        $update = array(
            'name'          => $nick_name,
            'updated_at'    => time2date()
        );
        // 更新
        $res = D('users')->where($where)->update($update);
        if ($res==false) {
            return json_error('更新失败，请重试', [], 10118);
        }else{
            // 队列   --添加搜索索引
            $params['uid'] = $user_info->id;
            $params['name'] = $nick_name;
            $params['mobile'] = empty($user_info->mobile) ? "" : $user_info->mobile;
            dispatch((new Elesticsearch(['type'=>'1', 'action'=>'edit', 'data'=>$params]))->onQueue('eleasticsearch'));

            return json_success('修改成功',[], 10119);
        }
    }

    /**
     * 确认修改性别
     * @return array
     */
    public function editSexSubmit()
    {
        // 用户性别
        $sex = IT('sex',true,'请选择性别', 10120);

        // 判断性别是否符合要求
        $check = [0,1,2];
        if (!in_array($sex,$check)) {
            EE('性别信息有误', 0, 10121);
        }
        // 更新条件及更新信息
        $uid = $this->uid;
        $where = array(
            ['id','=',$uid]
        );
        $update = array(
            'sex'           => $sex,
            'updated_at'    => time2date()
        );
        // 更新
        $res = D('users')->where($where)->update($update);
        if ($res==false) {
            return json_error('更新失败，请重试', [], 10118);
        }else{
            return json_success('修改成功',[], 10119);
        }
    }

    /**
     * @desc 确认修改个人资料
     * @param Request $request
     * @return array
     * @throws \Exception
     */
    public function editUserInfoSubmit(Request $request)
    {
        $params_list = $request->all();
        $receive_params = array('signature', 'birthday'); // 设置参数
        $update_data = array();

        // 接收参数
        foreach($receive_params as $params) {
            if(array_key_exists($params, $params_list)) {
                $update_data[$params] = $params_list[$params];
            }
        }

        if(empty($update_data)) {
            EE('请选择修改的个人资料', 0, 10244);
        }

        // 检测请求参数
        foreach($update_data as $key => $value) {
            switch ($key) {
                case "birthday":
                    if(!preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $value, $birthday)) {
                        EE('输入的生日有误', 0, 10242);
                    }
                    if(!checkdate($birthday[2], $birthday[3], $birthday[1])) {
                        EE('输入的生日有误', 0, 10242);
                    }
                    break;
                case "signature":
                    if(mb_strlen($value) > 100) {
                        EE('个性签名的长度不能超过100个字符', 0, 10243);
                    }
                    break;
                default:
                    EE('参数异常', 0, 10128);
                    break;
            }
        }

        $uid = $this->uid;
        $where = array(
            ['id','=',$uid]
        );
        $update_data['updated_at'] = time2date();

        // 更新
        $res = D('users')->where($where)->update($update_data);
        if ($res==false) {
            return json_error('更新失败，请重试', [], 10118);
        }else{
            return json_success('修改成功',[], 10119);
        }
    }

    /**
     * 确认修改手机号
     * @return array
     */
    public function editMobileSubmit()
    {
        // 用户手机号和验证码
        $mobile = IT('mobile',true,'请输入手机号', 10070);
        $code = IT('code',true,'请输入验证码', 10071);

        // 判断手机号是否正确
        if (!is_numeric($mobile)) {
            EE('手机号只能是纯数字', 0, 10074);
        }
        if (strlen($mobile) != 11) {
            EE('手机号必须为11位', 0, 10074);
        }
        // 判断验证码是否正确
        $flag = check_smscode($mobile,$code);
        if (empty($flag)) {
            EE('验证码错误', 0, 10077);
        }
        // 检测手机号是否注册
        $user = D('users')->where('mobile', $mobile)->first();
        if ($user) {
            return json_error('手机号已注册', [], 10122);
        }

        // 更新条件及更新信息
        $uid = $this->uid;
        $where = array(
            ['id','=',$uid]
        );
        $update = array(
            'mobile'        => $mobile,
            'updated_at'    => time2date()
        );
        // 更新
        $res = D('users')->where($where)->update($update);
        if ($res==false) {
            return json_error('更新失败，请重试', 0, 10118);
        }else{
            $member_data= MemberShip::where('mobile','=',$mobile)->where('status','=',0)->first();
            $share_data=  Shareholder::where('mobile','=',$mobile)->where([['status','=', 0],['data_audit','=',1],['fund_audit','=',1]])->first();
            if($member_data){
                //TODO 会员修改成功，如果users表中存在则修改状态成会员
                User::where('mobile','=',$mobile)->update(['membership'=>1]);
            }else{
                User::where('mobile','=',$mobile)->update(['membership'=>0]);
            }
            if($share_data){
                //Todo 股东修改成功，users表中存在该用户的话则修改成股东
                User::where('mobile','=',$mobile)->update(['role'=>1]);
            }else{
                User::where('mobile','=',$mobile)->update(['role'=>0]);
            }

            $params = [];
            // 队列   --添加搜索索引
            $params['uid'] = $this->uid;
            $params['name'] = $this->user_info->name;
            $params['mobile'] = $mobile;
            dispatch((new Elesticsearch(['type'=>'1', 'action'=>'edit', 'data'=>$params]))->onQueue('eleasticsearch'));

            return json_success('手机号绑定成功', [], 10123);
        }
    }

    /**
     * 确认修改头像
     * @return array
     */
    public function editAvatarSubmit(Request $request)
    {
        $img_file = IT('img_file', true, '请上传头像', 10124);
        if (!strpos($img_file, 'oss-cn-shenzhen.aliyuncs.com')) {
            return json_error('参数有误', [], 10032);
        }
        // 更新条件及更新信息
        $uid = $this->uid;
        $where = array(
            ['id','=',$uid]
        );
        $update = array(
            'avatar'        => $img_file,
            'updated_at'    => time2date()
        );

        $img_file = getSignUrl($img_file);
        $return = array(
            'img_url' => $img_file
        );

        // 更新
        $res = D('users')->where($where)->update($update);
        if ($res==false) {
            return json_error('更新失败，请重试', [], 10118);
        }else{
            $key = 'user:info:'.$uid;
            Redis::del($key);
            return json_success('头像上传成功', $return, 10125);
        }
    }

    /**
     * @return array
     * 我的二维码
     */
    public function qrcode()
    {
        $uid = $this->uid;
        $name = $this->user_info->name;
        $avatar = $this->user_info->avatar;
        $access_token = accesstoken();
        //$qrcode = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_str": "'.$uid.'"}}}'; //永久二维码
        $qrcode = '{"expire_seconds": 10, "action_name": "QR_STR_SCENE", "action_info": {"scene": {"scene_str": "'.$uid.'"}}}';//临时二维码

        $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$access_token;

        $result = https_request_s($url, $qrcode);
        $jsoninfo = json_decode($result, true);
        $ticket = $jsoninfo["ticket"];
        $url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($ticket);
        $imageInfo = downloadWeixinFile($url);
        //$imageInfo = https_request_s($url);
        $qrcode_url = $imageInfo['header']['url'];
        $data = [
            'uid' => $uid,
            'name'  =>  $name,
            'avatar'    =>  $avatar,
            'qrcode_url' => $qrcode_url,
        ];
        return json_success('ok',$data, 10000);
    }



    public function levelUpgrade(){

        $uid = $this->uid;
        $vip_list = DB::table('user_level_rule')->where([['status','=',1],['money','<>',0]])->get();
        $pay_type = config('basic.vip_pay_type');

        $wallet_data = Wallet::wallet($uid);

        foreach($pay_type as $k => $v){
            foreach($v as $key => $val){
                $wallet_type = $val['pay_type'];
                $pay_type[$k][$key]['balance'] =$wallet_data[$wallet_type]['balance'];
            }
        }
        foreach($vip_list as $k =>&$v){
            $v->viplevel = $v->vip_level;
            unset($v->created_at,$v->updated_at,$v->sorts,$v->status,$v->remarks,$v->vip_level);
        }
        $mobile = $this->user_info->mobile;
        $mobile = $mobile ?: 0;
        $data = [
            'bind_mobile'=>  $mobile,
            'avatar'    => $this->user_info->avatar,
            'vip_list'  =>  $vip_list,
            'pay_type'  =>  $pay_type,
        ];
        return json_success('ok',$data);
    }

    public function vipPay(){
        $uid = $this->uid;
        $walletClass = new Wallet();
        $order_log = new OrderLog();
        $wallet_data = Wallet::wallet($uid);
        $vcoin = $wallet_data['wallet_vcoin'];
        $id = IT('vip_id',true);    //会员id
        $pay_type = IT('pay_type',true);
        $pay_type_group_json = stripslashes(html_entity_decode(IT('pay_type_group_json')));
        $pay_type_group = json_decode($pay_type_group_json, true);

        $pay_type_three = '';
        $pay_type_three_count = 0;
        $pay_type_wallet_count = 0;
        $balance_not_enough = 0;
        $amount = 0;
        $pay_type_name = '';

        $vip = get_vip_by_id($id);
        $money = $vip['money'];
        foreach($pay_type_group as $pay_type2 => $amount_unit){
            // 如果是内部钱包
            if($wallet_pos = strpos($pay_type2,'wallet_') === 0){
                if(strstr($pay_type2,'vcoin')){
                    $balance = $vcoin['available'];
                    $balance_need = $amount_unit;
                    //判断余额是否足够
                    if($balance < $balance_need){
                        $balance_not_enough++;
                    }

                    $pay_type_group_all['wallet_vcoin'] = $amount_unit;
                    $pay_type_group_json = json_encode($pay_type_group_all);
                    $pay_type = $pay_type2;
                }
                $pay_type_wallet_count++;
            }else{
                $pay_type_three_count++;
                $pay_type_three = $pay_type2;
            }
            $pay_type_all = config('basic.vip_pay_type')['wap'];
            foreach($pay_type_all as $k => $v){
                if($v['pay_type'] == $pay_type2){
                    $pay_type_name = $v['name'];
                }
            }
            $amount += intval($amount_unit)?:0;
        }
        if($pay_type_three_count > 1){
            EE('存在多个第三方支付，请返回修改');
        }
        if($pay_type_three_count == 1){
            $pay_type = $pay_type_three;
        }else{
            $pay_type = $pay_type;
        }
        if($money != $amount){
            EE('下单金额不正确');
        }
        if($balance_not_enough){
            EE('V币余额不足');
        }

        //添加进user_level_order
        $ago_level = $this->user_info->isstockholder.'-'.$this->user_info->vip_level;
        $now_level = $vip['isstockholder'].'-'.$vip['vip_level'];
        $order_no = get_order_no();
        $user_level_order_data = [
            'uid'   =>  $uid,
            'order_no'  =>  $order_no,
            'pay_type'  =>  $pay_type,
            'pay_type_group_json'    =>  $pay_type_group_json,
            'ago_level'              => $ago_level,
            'now_level'              => $now_level,
            'money'                  => $money,
            'status'                 => 0,
            'created_at'             => date('Y-m-d H:i:s'),
            'updated_at'             => date('Y-m-d H:i:s'),
        ];
        DB::table('user_level_order')->insert($user_level_order_data);
        $order_log->addRecord($this->uid,$order_no,'订单生成成功','');

        $walletClass->user_id         =   $uid;
        $walletClass->order_no        =   $order_no;
        $walletClass->product_name    =   $vip['name'];
        $walletClass->return_url      =   '';
        $walletClass->notify_url      =   '';
        $walletClass->pay_type        =   $pay_type;
        $walletClass->pay_type_group  =   $pay_type_group_json;
        $data = $walletClass->unified();
        $data['order_no'] = $order_no;
        $data['product'] = $vip['name'];
        $data['pay_type'] = $pay_type_name;
        if($data['status'] == 1){
            return json_success('ok',$data);
        }
        return json_error('false',$data);

    }


    /**
     * @return array
     * 会员中心
     */
    public function vipHome(){
        $avatar = $this->user_info->avatar;
        $uid = $this->uid;
        $rewards = $this->user_info->rewards ?: 0;
        //$rewards = 0;
        $vip_indate = $this->user_info->vip_indate;
        $name = $this->user_info->name;
        $friend_id = IT('uid');
        $page = IT('page',1);
        $limit = IT('limit',10);
        $page = ($page-1) * $limit;
        $param = [
            'uid' => $uid,
            'limit' => $limit,
            'page' => $page
        ];
        $where  = [
            ['fu.status', '=' , 1],
            ['fu.type', '=', 1],
            ['fu.uid', '=' , $uid]
        ];
        $data = null;
        $data = Friend::getRecommendList($param, $where, $friend_id);
        $data['me'] = [
            'uid'   =>  $uid,
            'name'   =>  $name,
            'vip_indate'=>  $vip_indate,
            'avatar'    =>  $avatar,
            'rewards'   =>  $rewards/100,
        ];
        return json_success('ok',$data);
    }

    public function rewardsDetail(){
        $uid = $this->uid;
        $result = [];
        $where = [
            ['reasoncode','=',10002],
            ['intouserid','=',$uid],
            ['status','=',1],
            ['intousertypeid','=',3]
        ];
        $rewards_data = DB::table('fund_transfer')->where($where)->get();
        if($rewards_data){
            foreach($rewards_data as $k => $v){
                $result[$k]['date'] = $v->created_at;
                $result[$k]['name'] = '推荐奖励';
                $result[$k]['intoamount'] = round($v->intoamount / 100 , 2);
            }
            unset($rewards_data);
        }
        return json_success('ok',$result);
    }

    /**
     * 登出操作
     * @return array
     */
    public function logout()
    {
        $ticket = IT('ticket', '');
        $client_source = IT('ClientSource');

        D('user_tickets')->where([ ['ticket', $ticket], ['client_source', $client_source] ])->update(['status' => 2]);
        D('users')->where('id', $this->uid)->update(['registration_id' => '']);
        return json_success('ok');
    }

    /**
     * 设置registration_id  --作废
     * @return array
     */
    /*public function setRegistrationId()
    {
        $id = IT('registration_id', true, '缺少参数');
        $res = D('users')->where('id', $this->uid)->update(['registration_id' => $id]);
        if ($res === false) {
            return json_error('更新失败');
        }

        return json_success('ok');
    }*/

    /**
     * 申请添加好友
     * @return array
     */
    public function applyFriend()
    {
        $uid = IT('uid', true, '用户不存在', 10005);
        $apply_uid = $this->uid;

        if ($uid == $apply_uid)
            return json_error('不能添加自己为亲友圈', [], 10230);

        $user = User::find($uid);
        if (!$user) // || $user->status != '1'
            return json_error('用户不存在',[], 10005);

        // 检验黑名单
        $is_fail_friend = UserService::check_fail_friend($this->uid, $uid, 2);
        if($is_fail_friend['status'] == '1')
            return json_error($is_fail_friend['message'], [], $is_fail_friend['message_code']);

        $friend = D('friend')->where([ ['uid', $uid], ['friend_uid', $apply_uid], ['status', 1] ])->first();
        if ($friend)
            return json_error('该用户已是亲友，无需再次申请');

        $apply = D('friend_apply')->where([ ['uid', $uid], ['apply_uid', $apply_uid] ])->first();
        if ($apply)
            D('friend_apply')->where('id', $apply->id)->delete();

        $data = ['apply_uid' => $apply_uid, 'uid' => $uid, 'created_at' => time2date()];
        $res = D('friend_apply')->insert($data);

        if ($res) {
            // 推送
            if ($user->registration_id) {
                /*
                 *Pusher::message($user->registration_id, '有新的朋友邀请您成为亲友圈', ['type' => 3]);
                Pusher::alert($user->registration_id, '有新的朋友邀请您成为亲友圈');
                 *  */
                $getPushChannel = JpushMobile::getRowsArray([['registration_id', '=', $user->registration_id]]);
                // 消息推送
                if(!empty($getPushChannel) && !empty($getPushChannel['push_channel_id'])){

                    ////////////////////////////////////////////////////////////////////////////////////////////////
                    // 标题  --app 通过notify id 0处理业务 --透传
                    $data = [];
                    $push_channel_key = 'jpush';
                    if($getPushChannel['push_channel_id'] == 2){
                        $push_channel_key = 'hpush';
                    }else if($getPushChannel['push_channel_id'] == 3){
                        $push_channel_key = 'xmpush';
                    }

                    $data['channel_id'] = $getPushChannel['push_channel_id'];
                    $data['title'] = '邀请亲友'; // 登录标题
                    $data['content'] = '有新的朋友邀请您成为亲友圈';// 内容
                    $data['description'] = '有新的朋友邀请您成为亲友圈'; // 描述
                    $data['msg_type'] = config('push')[$push_channel_key]['type']['ospf'];  // 消息类型：1通知 0透传
                    $data['notify_id'] = 3;     // 通知id   --app 处理业务标识
                    $data['notify_foreground'] = 0; // 开启/关闭app在前台时的通知弹出 1:弹出通知  0 不弹出
                    $data['mobile_list'] = $getPushChannel['registration_id'];
                    $data['mobile_unique_code'] = IT('mobile_unique_code');
                    dispatch((new PushQueue(['type'=>'singlePush', 'data'=>$data]))->onQueue('push'));

                    // 保留原始功能
                    /*if($push_channel_key == 'jpush'){
                        // 发通知提示用户   --通知
                        unset($data['notify_id']);
                        $data['msg_type'] = config('push')[$push_channel_key]['type']['notify'];  // 消息类型：1通知 0透传
                        dispatch((new PushQueue(['type'=>'singlePush', 'data'=>$data]))->onQueue('push'));
                    }*/
                    ////////////////////////////////////////////////////////////////////////////////////////////////
                }
            }

            return json_success('申请成功');
        }

        return json_error('申请失败，请稍候再试');
    }

    /**
     * 申请好友列表
     * @param Request $request
     * @return array
     * 被申请人 查询列表
     */
    public function applyList(Request $request)
    {
        // 分页
        $page = IT('page') ? IT('page') : 1;
        $pagesize = IT('pagesize') ? IT('pagesize') : config('params')['pagesize'];
        $page = ($page-1)*$pagesize;

        $list = [];
        $hasNew = false;

        $uid = $this->uid;
        $where = [ ['friend_apply.uid', $uid], ['users.status', 1] ];
        $fields = [ 'friend_apply.id', 'friend_apply.apply_uid', 'friend_apply.uid', 'users.name', 'users.avatar', 'friend_apply.status', 'friend_apply.created_at' ];
        $total = D('friend_apply')->join('users', 'friend_apply.apply_uid', '=', 'users.id')->where($where)->count();
        if ($total > 0) {
            // 获取申请列表
            $list = D('friend_apply')->join('users', 'friend_apply.apply_uid', '=', 'users.id')->where($where)->skip(($page - 1) * $pagesize)->take($pagesize)->orderBy('friend_apply.id', 'desc')->get($fields);
            foreach ($list as &$l)
                $l->avatar = getSignUrl($l->avatar);
            if (!$hasNew && $l->status == '0')
                $hasNew = true;

            unset($l);
        }
        $totalPage = ceil($total / $pagesize);

        // 标识已读
        if ($hasNew)
            D('friend_apply')->where([ ['uid', $uid], ['status', 0] ])->update(['status' => 3]);

        return json_success('ok', ['totalPage' => $totalPage, 'list' => $list]);
    }

    /**
     * 删除申请
     * @return array
     */
    public function deleteApply()
    {
        $id = IT('id', true, '请选择要删除的申请');

        $apply = D('friend_apply')->find($id);
        if (!$apply) {
            return json_error('申请不存在');
        }

        $res = D('friend_apply')->where('id', $id)->delete();
        if ($res !== false) {
            return json_success('删除成功');
        }

        return json_error('删除失败');
    }

    /**
     * 改变申请状态
     * @return array
     */
    public function changeStatus()
    {
        $id = IT('id', true, '缺少参数');
        $status = IT('status', true, '缺少参数');

        // 申请记录
        $apply = D('friend_apply')->find($id);

        if ($status !== '2' && $status !== '1')
            return json_error('参数有误');
        if (!$apply || $apply->uid != $this->uid)
            return json_error('申请不存在');
        if ($apply->status != 0 && $apply->status != 3)
            return json_error('已同意或已拒绝该申请');

        $apply_relation_arr = [
            [$apply->apply_uid, $apply->uid],
            [$apply->uid, $apply->apply_uid],
        ];

        // 检验黑名单
        $is_fail_friend = UserService::check_fail_friend($apply->uid,$apply->apply_uid, 3);
        if($is_fail_friend['status'] == '1')
            return json_error($is_fail_friend['message']);

        $apply_status = true;
        DB::beginTransaction();
        // 更新申请状态
        $res = false !== D('friend_apply')->where('id', $id)->update(['status' => $status]);

        // 一次同意好友申请，生成两条记录
        if ($status === '1' && $res) {
            $time = time2date();
            foreach ($apply_relation_arr as $key=>$value){
                // 查询之前是否同意过，同意过的会在数据表中保存
                $friend = D('friend')->where([ ['uid', $value[0]], ['friend_uid', $value[1]] ])->first();
                if ($friend) {
                    $res = D('friend')->where('id', $friend->id)->update(['status' => 1, 'updated_at' => $time]);  // 同意过更新状态和时间
                } else {
                    $data = ['uid' => $value[0], 'friend_uid' => $value[1], 'created_at' => $time, 'updated_at' => $time];  // 否则插入数据
                    $res = $res && D('friend')->insert($data);
                }
                if(!$res) $apply_status = false;
            }

            // 推送消息 -------要修改-----------------------------------------------------------------------------------
            if ($apply_status){
                $user = D('users')->find($apply->apply_uid);

                if ($user && $user->registration_id) {

                    /*Pusher::message($user->registration_id, '对方已同意您的亲友圈邀请', ['type' => 3]);*/

                    $getPushChannel = JpushMobile::getRowsArray([['registration_id', '=', $user->registration_id]]);
                    // 消息推送
                    if (!empty($getPushChannel) && !empty($getPushChannel['push_channel_id'])) {

                        ////////////////////////////////////////////////////////////////////////////////////////////////
                        // 标题  --app 通过notify id 0处理业务 --透传
                        $data = [];
                        $push_channel_key = 'jpush';
                        if($getPushChannel['push_channel_id'] == 2){
                            $push_channel_key = 'hpush';
                        }else if($getPushChannel['push_channel_id'] == 3){
                            $push_channel_key = 'xmpush';
                        }

                        $data['channel_id'] = $getPushChannel['push_channel_id'];
                        $data['title'] = '邀请亲友'; // 登录标题
                        $data['content'] = '对方已同意您的亲友圈邀请';// 内容
                        $data['description'] = '对方已同意您的亲友圈邀请'; // 描述
                        $data['msg_type'] = config('push')[$push_channel_key]['type']['ospf'];  // 消息类型：1通知 0透传
                        //$data['notify_id'] = 3;     // 通知id   --app 处理业务标识
                        $data['notify_foreground'] = 0; // 开启/关闭app在前台时的通知弹出 1:弹出通知  0 不弹出
                        $data['mobile_list'] = $getPushChannel['registration_id'];
                        $data['mobile_unique_code'] = IT('mobile_unique_code');
                        // dispatch((new PushQueue(['type' => 'singlePush', 'data' => $data]))->onQueue('push'));

                        $data['notify_id'] = 5;     // 通知id   --app 处理业务标识
                        $data['extend'] = ['friend_uid'=>intval($apply->uid)];     // 通知id   --app 处理业务标识
                        dispatch((new PushQueue(['type' => 'singlePush', 'data' => $data]))->onQueue('push'));
                        ////////////////////////////////////////////////////////////////////////////////////////////////
                    }
                }
            }
        }

        if ($res && $apply_status) {
            DB::commit();
            return json_success('操作成功');
        }

        DB::rollback();
        return json_error('操作失败，请稍候再试');
    }

    /*
     * friend 通过uid 查询用户好友列表
     * */
    public function friendList(Request $request)
    {
        // 分页
        $page = IT('page') ? IT('page') : 1;
        $pagesize = IT('pagesize') ? IT('pagesize') : config('params')['pagesize'];
        $page = ($page-1)*$pagesize;

        $uid = $this->uid;

        $fields = [ 'friend.id', 'users.id as uid', 'users.name', 'users.avatar', 'friend.created_at' ];
        // 用户id ，好友状态 正常
        $where = [ ['friend.uid', $uid], ['friend.status', 1] ];

        $order = 'friend.updated_at desc';
        $list = D('friend')
            ->join('users','friend.friend_uid','=','users.id')
            ->where($where)
            ->orderByRaw($order)
            ->offset($page)
            ->limit($pagesize)
            ->get($fields);

        $list = $list ? $list->toArray() : [];

        // 获取可访问头像地址
        if(!empty($list))
            foreach ($list as $value)
                $value->avatar = getSignUrl($value->avatar);

        return json_success('ok', $list);
    }

    /**
     * 删除好友
     * @return array
     */
    public function deleteFriend()
    {
        $friend_id = IT('friend_uid',true, '缺少参数');

        $uid = $this->uid;
        $res_user = D("users")->where(['id' => $friend_id])->first();
        if(empty($res_user))
            EE("该亲友的微影号不存在!");

        $friend = D("friend")->where([['uid', '=', $uid], ['friend_uid', '=', $friend_id], ['status', '=', '1']])->first();
        if(empty($friend))
            return json_error("亲友不存在");
        $uid = $friend->uid;
        $friend_id = $friend->friend_uid;
        if($friend){
            $data_update = D("friend")->where([['uid', '=', $uid], ['friend_uid', '=', $friend_id]])->update(['status' => 0]);
            $upda =  D("friend")->where([['uid', '=', $friend_id], ['friend_uid', '=', $uid]])->update(['status' => 0]);
            return json_success('取消亲友成功');
        }
        return json_error('取消亲友失败');
    }

    /**
     * 搜索用户
     * @return array
     */
    public function searchFriend()
    {
        $uid = IT('uid', true, '缺少参数');

        $user_info = $this->user_info;
        if ($uid == $this->uid || $user_info->mobile == $uid)
            return json_error('不能邀请自己');

        $user = User::where('id', $uid)->first(['id', 'name', 'avatar', 'status', 'mobile']);
        if(empty($user)){
            $user = User::where('mobile', $uid)->first(['id', 'name', 'avatar', 'status', 'mobile']);
            if(empty($user))
                return json_error('未搜索到相关用户');
        }

        $data = [$uid, $this->uid];
        sort($data);
        $friend = D('friend')->where([ ['uid', $data[0]], ['friend_uid', $data[1]], ['status', 1] ])->first();
        $user->status = !$friend ? 0 : 1;

        if ($user->status === 0) {
            $apply = D('friend_apply')->where([ ['uid', $user->id], ['apply_uid', $this->uid] ])->first(['id','status']);
            if ($apply && ($apply->status == 0 || $apply->status == 3)) {
                $user->status = 2;  // 已邀请
            }
        }

        $user->avatar = getSignUrl($user->avatar);
        return json_success('ok', $user);
    }

    /*
     * 通讯录检测
     * */
    public function addressBook()
    {
        $invites = D('friend_invite')->where('uid', $this->uid)->get(['mobile', 'created_at']);

        $friends = D('friend')->where([['uid', $this->uid], ['status', 1]])->get(['friend_uid as uid']);
        $friends = $friends ? $friends->toArray() : [];
        $_friends = D('friend')->where([['friend_uid', $this->uid], ['status', 1]])->get(['uid']);
        $_friends = $_friends ? $_friends->toArray() : [];
        $friends = array_merge($friends, $_friends);

        $uids = [];
        foreach ($friends as $friend) {
            // 若通讯录好友已经是亲友
            $uids[] = $friend->uid;
        }

        if ($uids) {
            $users = D('users')->whereIn('id', $uids)->get(['mobile']);

            $mobiles = [];
            foreach ($users as $user) {
                if ($user->mobile) {
                    $mobiles[] = $user->mobile;
                }
            }
        }

        foreach ($invites as &$invite) {
            $invite->status = 1;
            if (isset($mobiles) && in_array($invite->mobile, $mobiles)) {
                $invite->status = 2;
            }
            $invite_allow = 0;
            if(date("Ymd", time()) != date("Ymd", strtotime($invite->created_at)))
                $invite_allow = 1;
            $invite->invite_allow = $invite_allow;
        }
        unset($invite);

        return json_success('ok', $invites);
    }

    /**
     * 群发短信
     * @param Request $request
     * @return array
     */
    public function groupSendMessage(Request $request)
    {
        IT('mobile', true, '请上传手机号', 10225);

        $data = $request->all();

        async_https_request_s(route('sendMessage'), $data);
        return json_success('ok');
    }

    /**
     * 发送短信   --通讯录增量群发
     * @return array
     */
    public function sendMessage()
    {
        $mobile = IT('mobile', true, '请上传手机号', 10225);
        $mobile = explode(',', $mobile);
        foreach ($mobile as $key => &$m) {
            $m = str_replace('+86', '', $m);
            if (!preg_match('/^(\+86(\-)?)?1[345789]\d{9}$/', str_replace(' ', '', $m))) {
                unset($mobile[$key]);
                continue;
            }

            // 群发关闭
            // D('friend_invite')->where([['uid', $this->uid], ['mobile', $m]])->delete();
            // D('friend_invite')->insert(['uid' => $this->uid, 'mobile' => $m, 'created_at'=> time2date()]);

            // 校验是否通过
            $temp_mss = MessagesSentSucceed::where(['msg_id'=>'0', 'msg_type' => 1, 'mobile' => $m])->first();
            if(!empty($temp_mss)){
                unset($mobile[$key]);
                continue;
            }
        }

        $mobiles = [];
        if (!empty(Redis::get('batch_send_message_sem'))) {
            $mobiles = json_decode(Redis::get('batch_send_message_sem'), true);
        }

        $mobile = array_values($mobile);
        $mobiles = array_unique(array_merge($mobiles, $mobile));

        // 保存短信号码池
        if (count($mobiles) >= 400) {
            $status = send_invite_msg(implode(',', $mobiles));
            if ($status) {
                $batch_mobile = [];
                foreach($mobiles as $value) {
                    $is_record = MessagesSentSucceed::where(['msg_id'=>'0', 'msg_type' => 1, 'mobile' => $value])->first();
                    if(empty($is_record)) {
                        $batch_mobile[] = ['msg_type' => 1, 'mobile' => $value, 'created_at' => time(), 'remark' => '发送通讯录邀请成功'];
                    }
                }
                if(!empty($batch_mobile)) {
                    MessagesSentSucceed::insert($batch_mobile);
                }

                Log::info(__FILE__, 'sendMessage', '发送邀请短信成功');
            } else {
                foreach($mobiles as $value) {
                    $batch_mobile[] = ['msg_type' => 1, 'mobile' => $value, 'created_at' => time(), 'remark' => '发送通讯录邀请失败'];
                }
                if(!empty($batch_mobile)) {
                    MessagesSentFailure::insert($batch_mobile);
                }
            }
            Redis::del('batch_send_message_sem');
        } else {
            Redis::set('batch_send_message_sem', json_encode($mobiles));
        }

        return json_success('ok');
    }

    /*
     * 加入黑名单/解除黑名单
     * //待解决  -- 黑名单用户获赞 // 关注数量 // 粉丝数量 // 收藏数量 // 亲友圈 // 好友列表 // 评论分支
     * */
    public function option_fail_friend(Request $request)
    {
        IT('friend_uid', true, '参数有误', 10032);
        IT('status', true, '参数有误', 10032);

        $friend_uid = $request->input('friend_uid');
        $status = $request->input('status');

        if($this->uid == $friend_uid)
            return json_error('不能添加自己为黑名单', [], 10226);

        DB::beginTransaction();
        $result = UserService::option_fail_friend($this->user_info, ['friend_uid'=>$friend_uid, 'status'=>$status]);
        if(isset($result['status']) && $result['status'] != 'success'){
            DB::rollBack();
            return json_error('操作失败', [], 10001);
        }

        $msg = '未知操作';
        $message_code = 10227;
        if($status == 1 && $result){
            $msg = '已加入黑名单';
            $message_code = 10228;
        }else if($status == 2 && $result){
            $msg = '已解除黑名单';
            $message_code = 10229;
        }

        DB::commit();
        return json_success($msg,[], $message_code);
    }

    /*
     * 黑名单列表
     * */
    public function fail_friend_list(Request $request)
    {

        // 分页
        $page = IT('page') ? IT('page') : 1;
        $rows = IT('rows') ? IT('rows') : 10;
        $page = ($page-1)*$rows;

        // 获取条件
        $select = array(
            'users.id as uid','users.name','users.mobile','users.avatar'
        );
        $where = array(
            ['wy_fail_friend.status', '=', 1],
            ['wy_fail_friend.uid', '=', $this->user_info->id],
        );

        $order = 'update_t desc';
        $data = D('wy_fail_friend')
            ->join('users','wy_fail_friend.friend_uid','=','users.id')
            ->where($where)
            ->orderByRaw($order)
            ->offset($page)
            ->limit($rows)
            ->get($select);
        foreach ($data as &$value)
            $value->avatar = empty($value->avatar) ? '' : getSignUrl($value->avatar);

        return json_success('ok', $data);
    }

    /*
     * 用户举报
     * */
    public function user_report (Request $request){

        IT('report_obj_id', true, '参数有误', 10032);
        IT('report_type', true, '参数有误', 10032);
        IT('type', true, '参数有误', 10032);

        $report_obj_id = $request->input('report_obj_id');
        $report_type = $request->input('report_type');
        $content = $request->input('content');
        $type = $request->input('type');
        $insert_date = [
            'report_obj_id' => intval($report_obj_id),
            'report_type' => intval($report_type),
            'type' => intval($type),
            'content' => $content,
            'uid' => $this->user_info->id,
            'report_time' => time2date()
        ];
        $update = UserReport::insert($insert_date);
        if($update){
            return json_success('举报成功', [], 10204);
        }else{
            return json_error('举报失败', [], 10205);
        }
    }

    /*
     * 通讯录邀请亲友圈
     *
     * app 调用用户手机发送短信  后台制作操作记录，不绑定关系
     * */
    public function sendApply(Request $request){

        IT('mobile', true, '参数有误', 10032);
        $mobile = trim($request->input('mobile'), ',');

        // 状态：1：已邀请，被邀请人未注册 2：已是亲友 3已邀请，被邀请人已注册
        $status = 1;
        $friend_user = D('users')->select(['id', 'registration_id'])->where([['mobile','=', $mobile]])->first();
        if (!empty($friend_user) && $this->uid == $friend_user->id)
            return json_error('不能添加自己为亲友圈', [], 10230);

        // 记录申请记录
        $friend_invite_id = D('friend_invite')->where([['uid','=', $this->uid], ['mobile','=', $mobile]])->value('id');
        if(!empty($friend_invite_id))
            $ins = D('friend_invite')->where('id', $friend_invite_id)->update(['status'=>$status, 'created_at'=>time2date()]);
        else
            $ins = D('friend_invite')->insert(['uid' => $this->uid, 'mobile' => $mobile, 'created_at'=> time2date(), 'status'=>$status]);
        if(!$ins)
            return json_error('操作失败', [], 10001);
        $create_share_result = UserService::create_share_info(2, $this->uid, $mobile);
        if(!$create_share_result)
            return json_error('操作失败', [], 10001);

        if(!empty($friend_user)){
            $status = 3;
            // 是否是亲友
            $friend = D('friend')->where([ ['uid', $this->uid], ['friend_uid', $friend_user->id], ['status', 1] ])->first();
            if(!empty($friend))
                $status = 2;
        }

        // 手机已注册账号
        if($status == '3'){
            // 申请与绑定
            $apply = D('friend_apply')->where([ ['apply_uid', $this->uid], ['uid', $friend_user->id] ])->first();
            if ($apply)
                D('friend_apply')->where('id', $apply->id)->delete();
            $data = ['apply_uid' => $this->uid, 'uid' => $friend_user->id, 'created_at' => time2date()];
            $res = D('friend_apply')->insert($data);
            if ($res) {
                // 推送
                if ($friend_user->registration_id) {
                    $getPushChannel = JpushMobile::getRowsArray([['registration_id', '=', $friend_user->registration_id]]);
                    // 消息推送
                    if(!empty($getPushChannel) && !empty($getPushChannel['push_channel_id'])){

                        ////////////////////////////////////////////////////////////////////////////////////////////////
                        // 标题  --app 通过notify id 0处理业务 --透传
                        $data = [];
                        $push_channel_key = 'jpush';
                        if($getPushChannel['push_channel_id'] == 2){
                            $push_channel_key = 'hpush';
                        }else if($getPushChannel['push_channel_id'] == 3){
                            $push_channel_key = 'xmpush';
                        }

                        $data['channel_id'] = $getPushChannel['push_channel_id'];
                        $data['title'] = trans('notice.10231');//'邀请亲友'; // 登录标题
                        $data['content'] = trans('notice.10232');//'有新的朋友邀请您成为亲友圈';// 内容
                        $data['description'] = trans('notice.10232');//'有新的朋友邀请您成为亲友圈'; // 描述
                        $data['msg_type'] = config('push')[$push_channel_key]['type']['ospf'];  // 消息类型：1通知 0透传
                        $data['notify_id'] = 3;     // 通知id   --app 处理业务标识
                        $data['notify_foreground'] = 0; // 开启/关闭app在前台时的通知弹出 1:弹出通知  0 不弹出
                        $data['mobile_list'] = $getPushChannel['registration_id'];
                        $data['mobile_unique_code'] = IT('mobile_unique_code');
                        dispatch((new PushQueue(['type'=>'singlePush', 'data'=>$data]))->onQueue('push'));
                        ////////////////////////////////////////////////////////////////////////////////////////////////
                    }
                }
                return json_success('申请成功', [], 10234);
            }
        }

        return json_success('ok', ['status'=>$status, 'uid'=>empty($friend_uid) ? 0 : $friend_uid]);
    }

    /*
     * 通讯录绑定
     * 最多关联存绑定3348个手机号
     *
     * */
    public function addressbookBinding(Request $request){
        IT('mobile', true, '参数有误', 10032);
        $mobile = trim($request->input('mobile'), ',');
        $uid = $this->uid;

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /// 校验绑定
        $mobile_arr = array_unique(explode(',', $mobile));
        if (count($mobile_arr) > 100)
            return json_error('每次绑定最多100条', [], 10235);

        $address_book_binding = D('ivy_address_book_binding')->where('uid', $this->uid)->first();

        // 提交的所有通讯录
        $addrss_book_mobile = [];
        foreach ($mobile_arr as $key => $value) {
            // 检验是否已经绑定过了
            if(!empty($address_book_binding) && strpos($address_book_binding->addrss_book_mobile, $value) !== false)
                continue;
            $addrss_book_mobile[] = $value;
        }

        // 绑定有效注册的用户
        $addrss_book_uid = [];
        $userLiset = User::select(['id', 'mobile'])->whereIn('mobile', $mobile_arr)->get();
        foreach ($userLiset as $k=>$val){
            // 不能自己绑定自己
            if($val->id == $uid)
                continue;
            // 检验是否已经绑定过了
            if(!empty($address_book_binding) && in_array($val->id, explode(',', $address_book_binding->addrss_book_uid)))
                continue;
            $addrss_book_uid[] = $val->id;
        }

        // 已绑定
        if(!empty($address_book_binding)){
            $update['option_time'] = time();
            if(!empty($addrss_book_mobile))
                $update['addrss_book_mobile'] = empty($address_book_binding->addrss_book_mobile) ? implode(',', $addrss_book_mobile) : $address_book_binding->addrss_book_mobile.','.implode(',', $addrss_book_mobile);
            if(!empty($addrss_book_uid))
                $update['addrss_book_uid'] = empty($address_book_binding->addrss_book_uid) ? implode(',', $addrss_book_uid) : $address_book_binding->addrss_book_uid.','.implode(',', $addrss_book_uid);
            $ins = D('ivy_address_book_binding')->where('id', $address_book_binding->id)->update($update);
        }else{
            $insertArr['uid'] = $uid;
            $insertArr['option_time'] = time();
            if(!empty($addrss_book_mobile))
                $insertArr['addrss_book_mobile'] = implode(',', $addrss_book_mobile);
            if(!empty($addrss_book_mobile))
                $insertArr['addrss_book_uid'] = implode(',', $addrss_book_uid);
            $ins = D('ivy_address_book_binding')->insert($insertArr);
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        if(!$ins)
            return json_error('绑定异常', [], 10236);

        // 创建队列发送短信
        SnsService::send_message_queue($mobile, 0, 1, true);
        return json_success('绑定成功', [], 10237);
    }

    /*
     * 通讯录绑定检测
     * */
    public function addressbookCheck(Request $request){
        $address_book_binding = D('ivy_address_book_binding')->where('uid', $this->uid)->first();
        $data = [];
        if(!empty($address_book_binding)){
            $list = User::select(['id', 'mobile'])->whereIn('id', explode(',',  $address_book_binding->addrss_book_uid))->get();
            $temp_arr = [];
            foreach ($list as $key=>$value){
                $temp_arr['mobile'] = $value->mobile;
                $temp_arr['uid'] = $value->id;
                $data[] = $temp_arr;
            }
        }
        return json_success('ok', $data, 10000);
    }

    /**
     * @desc 获取最新活动及邀请人列表
     */
    public function invitationUserDetails(Request $request)
    {
        $uid = $this->uid;
        $page = $request->input('page', 1);
        $page_size = $request->input('pagesize', 20);
        $activity_fields = ['content', 'start_time', 'end_time', 'reward_amount', 'status', 'created_at', 'updated_at'];
        $activity_data = ActivityConfig::select($activity_fields)->where([['status', '=', ActivityEnum::ACTIVITY_STATUS_VALID], ['end_time', '>', time()], ['activity_type', '=', ActivityEnum::ACTIVITY_TYPE_INVITE]])->orderBy('updated_at', 'desc')->first();
        if($activity_data) {
            $activity_data = $activity_data->toArray();
            $activity_data['start_time'] = date('Y-m-d H:i:s');
            $activity_data['end_time'] = date('Y-m-d H:i:s');
        } else {
            $activity_data = null;
        }
        $share_num = User::where(['id' => $uid])->first(['share_num']);

        $total = User::where(['parent_id' => $uid])->count();
        $total_page = ceil($total / $page_size);
        $offset = ($page - 1) * $page_size;
        $user_fields = ['name', 'avatar', 'real_name', 'mobile', 'share_num', 'download_time'];
        $user_list = User::select($user_fields)->where(['parent_id' => $uid])->skip($offset)->take($page_size)->orderBy('download_time', 'desc')->get();
        foreach($user_list as &$user) {
            $user['avatar'] = $user['avatar'] ? getSignUrl($user['avatar']) : '';
            $user['download_time'] = date('m-d H:i', $user['download_time']);
        }
        $qr_code = config('app.url').'/api/Sharing_links?share_type=main&channel=wx&uid='.$uid;

        return json_success('ok', ['total' => $total, 'totalPage' => $total_page, 'list' => $user_list, 'activity_config' => $activity_data, 'qr_code' => $qr_code, 'share_num' => (int)$share_num->share_num]);
    }

    /**
     * @desc 视频聊天之创建房间号
     */
    public function video_chat()
    {
        $uid = $this->uid;
        $recipient_uid = IT('recipient_uid', true, '参数有误', 10032);

        // 处理并发问题(互相发送)
        $both_key = $uid < $recipient_uid ? ($uid.'_'.$recipient_uid) : ($recipient_uid.'_'.$uid);
        $both_key = 'video_chat:room:'.$both_key;
        if(!Redis::setnx($both_key, 1)) {
            return json_error('对方正在忙', [], 10256);
        }

        // 接收人并发问题(多人发送给同一个人)
        $recipient_key = 'video_chat:room:recipient_'.$recipient_uid;
        if(!Redis::setnx($recipient_key, 1)) {
            return json_error('对方正在忙', [], 10256);
        }

        $video_chat = new VideoChatService();
        $rs = $video_chat->video_chat($uid, $recipient_uid);

        Redis::del($both_key);
        Redis::del($recipient_key);
        if($rs['code'] == 10258) {
            return json_success($rs['msg'], $rs['data'], $rs['code']);
        }
        if($rs['code'] != 0) {
            return json_error($rs['msg'], [], $rs['code']);
        }

        return json_success('ok', $rs['data']);
    }

    /**
     * @desc 修改视频聊天的状态
     */
    public function modify_video_chat_status()
    {
        $uid = $this->uid;
        $status = IT('status', true, '参数有误', 10032);
        $room_id = IT('room_id', true, '参数有误', 10032);
        $duration_time = IT('duration_time');

        $video_chat = new VideoChatService();
        $rs = $video_chat->modify_video_chat_status($uid, $room_id, $status, $duration_time);
        if($rs['code'] != 0) {
            return json_error($rs['msg'], [], $rs['code']);
        }

        return json_success('ok', []);
    }

    /**
     * @desc 免邀请码注册参数
     * @return array
     */
    public function user_invitation_code() {
        $user_info = $this->user_info;
        $invitation_code_info = UserInvitationCode::where(['uid' => $user_info->id])->first(['invitation_code']);
        $data = ['invitation_code' => $invitation_code_info->invitation_code];
        return json_success('ok', $data);
    }
}